import schedule
import time
import logging
import configparser
import os
from ollama import Client, ChatResponse
from datetime import datetime

# 引入自定义模块
from utils.get_hot_news import weibo
from utils.sendEmails import format_email_message, send_email


os.chdir(os.path.dirname(os.path.abspath(__file__)))

# 设置日志记录器
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# logger.setLevel(logging.DEBUG)

# 创建格式化器，格式化日志输出
log_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')

# 创建文件处理器，将日志写入文件
log_file = "task_log.log"
file_handler = logging.FileHandler(log_file)
file_handler.setFormatter(log_formatter)

# 创建控制台处理器，将日志输出到控制台
console_handler = logging.StreamHandler()
console_handler.setFormatter(log_formatter)

# 添加处理器到日志记录器
logger.addHandler(file_handler)
logger.addHandler(console_handler)

# 创建 ConfigParser 实例
config = configparser.ConfigParser()

# 读取配置文件
config.read('config.ini')

# 获取邮箱相关的配置参数
sender = config.get('email', 'sender')
sender_name = config.get('email', 'sender_name')
mail_license = config.get('email', 'mail_license')
receiver_name = config.get('email', 'receiver_name')

# 存储消息的变量
global news_list
global email_message_body
news_list = []
email_message_body = ""

def main():
    logger.info("Task: 定时拉取热点信息与自动发送邮件 --> 开始运行")
    
    run_once()
    remaining_seconds = seconds_to_next_hour()
    logger.info("将在 %d 秒后开始运行定时任务..." % remaining_seconds)
    time.sleep(remaining_seconds)
    run_once()
    
    # 每小时抓取一次热搜数据
    schedule.every().hour.do(run_once)  # 每小时抓取一次热搜数据

    # 设置每天定时任务，定时发送邮件
    schedule.every().day.at("06:00").do(auto_send_email)
    schedule.every().day.at("14:00").do(auto_send_email)
    schedule.every().day.at("22:00").do(auto_send_email)
    
    # 保持脚本持续运行，并检查是否有定时任务需要执行
    while True:
        schedule.run_pending()
        time.sleep(30)

def run_once():
    '''
    每小时运行一次
    执行任务：
        1. 初始化消息列表
        2. 获取新闻列表，与历史数据去重
        3. 更新推送信息
        4. 添加到今日的消息列表
    '''
    global news_list
    global email_message_body
    # 获取热搜数据
    try:
        get_url_info, _, title_list = weibo('weibo_news_DB')
    except Exception as e:
        logger.error(f"获取热搜数据失败，错误信息: {e}")
        get_url_info = False
    time_stamp = time.strftime("%Y.%m.%d - %H:%M:%S", time.localtime())
    
    email_message_body += "\n" + time_stamp + "\n"
    
    # 如果成功获取热搜数据，去重并更新列表
    if get_url_info:
        for title in title_list:
            if title not in news_list:
                news_list.append(title)
                # 编辑邮件内容
                email_message_body += f"  - {title}\n"
        logger.info(f"热搜数据拉取成功")
    else:
        email_message_body += f"  - 热搜数据拉取失败\n"
        logger.error(f"热搜数据拉取失败")
    
    if len(news_list) > 50:
        news_list = news_list[-50:]


def auto_send_email():
    '''
    自动发送邮件
    '''
    global news_list
    global email_message_body
    summary_keywords = summary_keywords_from_message(email_message_body)
    email_message_body = "关键词总结如下：\n" + summary_keywords + "\n\n" + email_message_body
    subject_content = f"微博热搜 {time.strftime('%Y.%m.%d', time.localtime())}"
    message = format_email_message(
        sender_name=sender_name,
        receiver_name=receiver_name,
        email_Subject=subject_content,
        email_text=email_message_body,
    )
    try:
        send_email(sender=sender,
                mail_license=mail_license,
                receiver=receiver_name,
                msg=message)
        logger.info(f"邮件发送成功: \n"
                    f"subject_content: {subject_content}\n"
                    f"receiver_name: {receiver_name}\n"
                    f"email_message_body(len): {len(email_message_body)}\n")
    except Exception as e:
        logger.error(f"邮件发送失败，错误信息: {e}")
        
    
    # 重置消息体
    email_message_body = ""
    logger.info(f"消息体列表重置")

# 总结信息
def summary_keywords_from_message(email_message_body):
    client = Client(host='http://host.docker.internal:11434', headers={'x-some-header': 'some-value'})
    model_name = ['deepseek-r1:8b', 'Qwen2.5:7b']
    response : ChatResponse = client.chat(model=model_name[0], messages=[
    {
      'role': 'user',
      'content':
          f'\n信息列表如下：\n{email_message_body}'
          '根据以上提供的热点信息列表，提取出其中关键词，列举2-5个。只回复我关键词，不输出其他任何内容。'
          '示例：关键词1；关键词2；关键词3……关键词5。\n'
          },
  ])
    return response.message.content


def seconds_to_next_hour():
    # 获取当前时间
    now = datetime.now()
    current_seconds = now.minute * 60 + now.second
    seconds_in_next_hour = 3600
    remaining_seconds = seconds_in_next_hour - current_seconds
    
    return remaining_seconds


if __name__ == "__main__":
    main()
    # auto_send_email()

